package java_ex.controller;

import java.util.LinkedList;
import java.util.List;

import javax.swing.JTextArea;
import javax.swing.SwingWorker;

public class PrimeNumber extends SwingWorker<List<Integer>, Integer> {

    private int max, current = 3;
    private JTextArea result;
    private List<Integer> results = new LinkedList<Integer>();
    
    public PrimeNumber(int max, JTextArea result){
        this.result = result;
        this.max = max;
        results.add(1);
        results.add(2);
        results.add(3);        
    }
    
    @Override
    protected List<Integer> doInBackground() throws Exception {
        
        while(current < max){
            
            if(isPrime(current)){
                firePropertyChange("primefound", 0, current);                
                results.add(current);
            }
            firePropertyChange("nextnumber", current, current + 2);    
            current+=2;    
        }
        
        return results;
    }

    private boolean isPrime(int number){
        int teiler = 3;
        if(number % 2 == 0) return false;
        while(teiler * teiler <= number){
            if(number % teiler == 0){
                return false;
            }else{
                teiler+=2;
            }
        }
        return true;
    }
}
